package com.bytesizedhosting.api.android.darthcrap.screens.maintabs;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TextView;

import com.bytesizedhosting.api.android.darthcrap.ExtendedActivity;
import com.bytesizedhosting.api.android.darthcrap.NullArgumentException;
import com.bytesizedhosting.api.android.darthcrap.R;
import com.bytesizedhosting.api.android.darthcrap.api.APIController;
import com.bytesizedhosting.api.android.darthcrap.api.APIData.Account;
import com.bytesizedhosting.api.android.darthcrap.components.accordian.Accordian;
import com.bytesizedhosting.api.android.darthcrap.components.accordian.AccordianEntry;

public class AccountsTab extends ExtendedActivity {
	private static Accordian.StateContainer objStateContainer = new Accordian.StateContainer();
	private Accordian objAccordian = null;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accountstab);
        
        this.objAccordian = (Accordian)findViewById(R.id.accMain);
        this.objAccordian.setStateContainer(objStateContainer);
        
        int intCount = 0;
        for (Account objAccount : APIController.getData().getAccountIterator()) {
        	intCount++;
        	objAccordian.addEntry(new AccountEntry(objAccount));
        }
        
        this.objAccordian.restoreState();
        
        findViewById(R.id.lblNoSeedboxes).setVisibility((intCount==0)?View.VISIBLE:View.GONE);
        this.objAccordian.setVisibility((intCount!=0)?View.VISIBLE:View.GONE);
    }
    
    public void onConfigurationChanged(Configuration objNewConfig) {
    	this.objAccordian.holdState();
    	super.onConfigurationChanged(objNewConfig);
    }
    
    private static class AccountEntry extends AccordianEntry {
    	private Account objAccount = null;
    	
    	public AccountEntry(Account objAccount) {
    		super(objAccount.getServerName(),objAccount.getCalculatedQuotaUsage() > objAccount.getCalculatedQuotaSoftLimit());
    		NullArgumentException.testArguments(objAccount);
    		this.objAccount = objAccount;
    	}
    	
		@Override
		protected void buildEntryView(LayoutInflater objInflater, final LinearLayout objRootLayout) {
			DecimalFormat objNumberFormat = new DecimalFormat("#00.00");
			SimpleDateFormat objDateFormat = new SimpleDateFormat("dd MMMM yyyy"); 
			
			TableLayout objTable = (TableLayout)objInflater.inflate(R.layout.accountsitem,objRootLayout,false);
			setText(objTable, R.id.lblUsage,(objNumberFormat.format(objAccount.getCalculatedQuotaUsage()) + "GB / " + objNumberFormat.format(objAccount.getCalculatedQuotaSoftLimit()) + "GB (" + objNumberFormat.format((objAccount.getCalculatedQuotaUsage() / objAccount.getCalculatedQuotaSoftLimit()) * 100) + "%)"));
			
			ProgressBar objPB = (ProgressBar)objTable.findViewById(R.id.pbUsage);
			if (objAccount.getCalculatedQuotaUsage() > objAccount.getCalculatedQuotaSoftLimit()) {
				objPB.setProgressDrawable(objRootLayout.getResources().getDrawable(R.drawable.progress_horizontal_red));
				objPB.setMax((int)(objAccount.getCalculatedQuotaHardLimit()*10));
				objPB.setProgress((int)(objAccount.getCalculatedQuotaSoftLimit()*10));
				objPB.setSecondaryProgress((int)(objAccount.getCalculatedQuotaUsage()*10));
				objTable.findViewById(R.id.trHardLimit).setVisibility(View.VISIBLE);
				setText(objTable,R.id.lblHardLimit,objNumberFormat.format(objAccount.getCalculatedQuotaHardLimit())+"GB");
			}
			else {
				objPB.setProgressDrawable(objRootLayout.getResources().getDrawable(R.drawable.progress_horizontal_green));
				objPB.setMax((int)(objAccount.getCalculatedQuotaSoftLimit()*10));
				objPB.setProgress((int)(objAccount.getCalculatedQuotaUsage()*10));
				objPB.setSecondaryProgress(0);
				objTable.findViewById(R.id.trHardLimit).setVisibility(View.GONE);
			}
			
			setText(objTable,R.id.lblClient,objAccount.getClientName());
			if (objAccount.getPaidTillDate() != null) { 
				setText(objTable,R.id.lblDatePaid,objDateFormat.format(objAccount.getPaidTillDate()));
			}
			else {
				setText(objTable,R.id.lblDatePaid,objRootLayout.getContext().getResources().getString(R.string.accounts_nopaidtilldate));				
			}
			setText(objTable,R.id.lblUpgradeable,((objAccount.isUpgradeAvailable())?getString(objRootLayout,R.string.generic_yes):getString(objRootLayout,R.string.generic_no)));
			setText(objTable,R.id.lblWebUI,Html.fromHtml("<a href='" + objAccount.getWebUILink() + "'>" + objAccount.getWebUILink() + "</a>")).setOnClickListener(new View.OnClickListener() {
				private int intChosenChoice = -2;
				
				@Override
				public void onClick(final View objView) {
					intChosenChoice = -1;
					AlertDialog.Builder objBuilder = new AlertDialog.Builder(objView.getContext());
					objBuilder.setTitle(getString(objRootLayout,R.string.accounts_openwebuiwith));
					objBuilder.setSingleChoiceItems(new String[] {getString(objRootLayout,R.string.accounts_opt_internet),getString(objRootLayout,R.string.accounts_opt_transdroid)}, 0, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface objInterface, int intChoice) {
							intChosenChoice = intChoice;
						}
					});
					objBuilder.setPositiveButton(getString(objRootLayout,R.string.generic_open), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface objInterface, int intChoice) {
							if (intChosenChoice == 0) {
								objView.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(objAccount.getWebUILink())));
							}
							else if (intChosenChoice == 1) {
								AlertDialog.Builder objBuilder = new AlertDialog.Builder(objView.getContext());
								objBuilder.setTitle(getString(objRootLayout,R.string.accounts_cannotopenwebui));
								objBuilder.setMessage(getString(objRootLayout,R.string.accounts_notransdroid));
								objBuilder.setNeutralButton(getString(objRootLayout,R.string.generic_ok), new Dialog.OnClickListener() {
									@Override
									public void onClick(DialogInterface objInterface, int intChoice) {}
								});
								objBuilder.show();
							}
						}
					});
					objBuilder.setNegativeButton(getString(objRootLayout,R.string.generic_cancel), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface objInterface, int intChoice) {
							objInterface.dismiss();
						}
					});
					objBuilder.show();
				}
			});
	
			objRootLayout.addView(objTable);
		}
		
		private String getString(LinearLayout objRootLayout, int intStringResourceID) {
			return objRootLayout.getContext().getResources().getString(intStringResourceID);
		}
		
		private TextView setText(ViewGroup objViewGroup, int intID, CharSequence strText) {
			TextView objTextView = (TextView)objViewGroup.findViewById(intID);
			objTextView.setText(strText);
			return objTextView;
		}

		@Override
		public int hashCode() {
			return this.objAccount.hashCode();
		}
    }
}